﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lacrima.Gobang.App
{
    public partial class ServerConfig : Form
    {
        private static byte[] result = new byte[1024];
        //设定服务器IP地址  
        private IPAddress IP { get; set; }
        private Socket clientSocket { get; set; }
        private int Port { get; set; }

        public ServerConfig()
        {
            InitializeComponent();
            this.tbIpAddres.Text = "192.168.1.160";
            this.tbPort.Text = "8885";
            this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        private void btnListen_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.clientSocket.IsBound && this.clientSocket.Connected)
                {
                    this.tbDialog.AppendText("已连接到服务器，如需更改连接服务器请在断开连接后重试！\r\n");
                }
                else
                {
                    this.IP = IPAddress.Parse(this.tbIpAddres.Text);
                    this.Port = int.Parse(this.tbPort.Text);
                    this.tbDialog.AppendText("正在连接，请稍后...\r\n");
         
                    // 此处建议使用backgroundworker
                    //配置服务器IP与端口  
                    Task.Run(() =>
                    {
                        try
                        {
                            this.clientSocket.Connect(new IPEndPoint(this.IP, this.Port));
                        }
                        catch(Exception ex)
                        {
                            //throw ex;
                        }
                    })
                    .ContinueWith(o => this.Invoke((EventHandler)(delegate
                    {
                        if (o.Exception == null && clientSocket.Connected)
                        {
                            //通过clientSocket接收数据  
                            int receiveLength = clientSocket.Receive(result);
                            this.tbDialog.AppendText(string.Format("接收服务器消息：{0}\r\n", Encoding.ASCII.GetString(result, 0, receiveLength)));
                            this.tbDialog.AppendText("连接成功！\r\n");
                        }
                        else
                        {
                            this.tbDialog.AppendText("连接失败！\r\n");
                        }
                    })));
                }
            }
            catch(SocketException ex)
            {
                this.tbDialog.AppendText(string.Concat(ex.Message,"\r\n"));
            }
            catch (InvalidOperationException ex)
            {
                this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                this.clientSocket.Connect(new IPEndPoint(this.IP, this.Port));
                int receiveLength = clientSocket.Receive(result);
                this.tbDialog.AppendText(string.Format("接收服务器消息：{0}\r\n", Encoding.ASCII.GetString(result, 0, receiveLength)));
                this.tbDialog.AppendText("连接成功！\r\n");
            }
            catch (Exception ex)
            {
                this.tbDialog.AppendText("服务器连接失败，请检查！\r\n");
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.tbDialog.Clear();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.tbSend.Text)) return;
                string userName = System.Net.Dns.GetHostName();
                clientSocket.Send(Encoding.ASCII.GetBytes(this.tbSend.Text));
                this.tbDialog.AppendText(string.Format("{0} {1}\r\n{2}\r\n", userName, DateTime.Now, this.tbSend.Text));
            }
            catch(Exception ex)
            {
                this.Disconnect(this.clientSocket);
            }
            finally
            {
                this.tbSend.Clear();
            }
        }

        private void ServerConfig_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Disconnect(this.clientSocket);
            this.clientSocket.Close();
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            this.Disconnect(this.clientSocket);
        }

        private void Disconnect(Socket socket)
        {
            if (socket != null && socket.Connected)
            {
                socket.Shutdown(SocketShutdown.Both);
                this.tbDialog.AppendText("断开连接！\r\n");
            }
        }
    }
}
